import React, { useState, useEffect, useCallback } from 'react';
import AudioPlayer, { PlayMode } from './components/AudioPlayer';
import LrcDisplay from './components/LrcDisplay';
import StorySelector from './components/StorySelector';
import { parseLrc, getCurrentLrcIndex, LrcLine, ParsedLrc } from './utils/lrcParser';
import './App.css';

interface Story {
  id: string;
  title: string;
  description: string;
  audioUrl: string;
  lrcFile: string | null;
}

const App: React.FC = () => {
  const [stories, setStories] = useState<Story[]>([]);
  const [currentStory, setCurrentStory] = useState<Story | null>(null);
  const [lrcData, setLrcData] = useState<ParsedLrc | null>(null);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [playMode, setPlayMode] = useState<PlayMode>('normal');
  const [playbackRate, setPlaybackRate] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isStorySelectorOpen, setIsStorySelectorOpen] = useState(false);
  
  // 句子重复相关状态
  const [sentenceStartTime, setSentenceStartTime] = useState<number | undefined>();
  const [sentenceEndTime, setSentenceEndTime] = useState<number | undefined>();

  // 获取故事列表
  useEffect(() => {
    const fetchStories = async () => {
      try {
        const response = await fetch('' +
            '/api/stories');
        if (!response.ok) throw new Error('Failed to fetch stories');
        const data = await response.json();
        setStories(data);
        
        // 自动选择第一个故事
        if (data.length > 0) {
          setCurrentStory(data[0]);
        }
      } catch (err) {
        setError('无法加载故事列表');
        console.error('Error fetching stories:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchStories();
  }, []);

  // 加载LRC文件
  useEffect(() => {
    const loadLrc = async () => {
      if (!currentStory?.lrcFile) {
        setLrcData(null);
        return;
      }

      try {
        const response = await fetch(`/api/lrc/${currentStory.lrcFile}`);
        if (!response.ok) throw new Error('Failed to fetch LRC');
        const data = await response.json();
        const parsed = parseLrc(data.content);
        setLrcData(parsed);
      } catch (err) {
        console.error('Error loading LRC:', err);
        setLrcData(null);
      }
    };

    loadLrc();
  }, [currentStory]);

  // 获取当前歌词索引
  const currentLrcIndex = lrcData ? getCurrentLrcIndex(lrcData.lines, currentTime) : -1;

  // 处理音频跳转
  const handleSeek = useCallback((time: number) => {
    setCurrentTime(time);
  }, []);

  // 处理歌词行点击
  const handleLrcLineClick = useCallback((index: number) => {
    if (!lrcData) return;
    
    const line = lrcData.lines[index];
    const nextLine = lrcData.lines[index + 1];
    
    // 跳转到指定时间
    handleSeek(line.time);
    
    // 如果是句子重复模式，设置重复范围
    if (playMode === 'repeat-sentence') {
      setSentenceStartTime(line.time);
      setSentenceEndTime(nextLine ? nextLine.time : duration);
    }
    
    // 开始播放
    if (!isPlaying) {
      setIsPlaying(true);
    }
  }, [lrcData, playMode, duration, isPlaying, handleSeek]);

  // 处理播放模式变化
  const handlePlayModeChange = useCallback((mode: PlayMode) => {
    setPlayMode(mode);
    
    // 如果切换到句子重复模式，设置当前句子为重复范围
    if (mode === 'repeat-sentence' && lrcData && currentLrcIndex >= 0) {
      const currentLine = lrcData.lines[currentLrcIndex];
      const nextLine = lrcData.lines[currentLrcIndex + 1];
      setSentenceStartTime(currentLine.time);
      setSentenceEndTime(nextLine ? nextLine.time : duration);
    } else if (mode !== 'repeat-sentence') {
      // 清除句子重复范围
      setSentenceStartTime(undefined);
      setSentenceEndTime(undefined);
    }
  }, [lrcData, currentLrcIndex, duration]);

  // 处理故事选择
  const handleStorySelect = useCallback((story: Story) => {
    setCurrentStory(story);
    setIsPlaying(false);
    setCurrentTime(0);
    setSentenceStartTime(undefined);
    setSentenceEndTime(undefined);
  }, []);

  if (loading) {
    return (
      <div className="container">
        <div className="loading">
          <p>正在加载...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container">
        <div className="card">
          <h2>错误</h2>
          <p>{error}</p>
        </div>
      </div>
    );
  }

  if (stories.length === 0) {
    return (
      <div className="container">
        <div className="card">
          <h2>没有找到音频文件</h2>
          <p>请确保在项目目录下有MP3文件和对应的LRC文件</p>
        </div>
      </div>
    );
  }

  return (
    <div className="app">
      <div className="container">
        <header className="app-header">
          <p>每天一个故事 - 英语学习助手</p>
        </header>

        {/* 故事选择按钮 */}
        {stories.length > 1 && (
          <div className="card story-selector-button">
            <button 
              className="btn btn-primary story-select-btn"
              onClick={() => setIsStorySelectorOpen(true)}
            >
              <div>
                <div>📚 选择故事</div>
                <small>当前: {currentStory?.title || '未选择'}</small>
              </div>
            </button>
          </div>
        )}

        {currentStory && (
          <>
            {/* 音频播放器 */}
            <div className="card">
              <h3>{currentStory.title}</h3>
              <p>{currentStory.description}</p>
              <AudioPlayer
                audioUrl={`http://localhost:8082${currentStory.audioUrl}`}
                currentTime={currentTime}
                duration={duration}
                isPlaying={isPlaying}
                playMode={playMode}
                playbackRate={playbackRate}
                onTimeUpdate={setCurrentTime}
                onDurationChange={setDuration}
                onPlay={() => setIsPlaying(true)}
                onPause={() => setIsPlaying(false)}
                onSeek={handleSeek}
                onPlayModeChange={handlePlayModeChange}
                onPlaybackRateChange={setPlaybackRate}
                sentenceStartTime={sentenceStartTime}
                sentenceEndTime={sentenceEndTime}
              />
            </div>

            {/* 歌词显示 */}
            {lrcData && (
              <div className="card">
                <LrcDisplay
                  lrcLines={lrcData.lines}
                  currentIndex={currentLrcIndex}
                  onLineClick={handleLrcLineClick}
                />
              </div>
            )}
          </>
        )}
      </div>
      
      {/* 故事选择弹窗 */}
      <StorySelector
        stories={stories}
        currentStory={currentStory}
        isOpen={isStorySelectorOpen}
        onClose={() => setIsStorySelectorOpen(false)}
        onSelect={handleStorySelect}
      />
    </div>
  );
};

export default App;